package com.lx.controller;

import com.lx.Exception.BusinessException;
import com.lx.domain.machine;
import com.lx.serv.impl.MachineServImpl;
import com.lx.utill.JwtUtill;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin
@RequestMapping(value = "/machine")
public class MachineController {
    //    private String password = "admin";
//    private String Coaname = "admin";
    @Autowired
    private MachineServImpl machine;

    @GetMapping
    public Result getAll(@RequestHeader("token") String token) {
        if (JwtUtill.VerifyToken(token)) {
            return new Result(Code.GET_SUCCESS, "获取成功", machine.getAll());
        }
        return new Result(Code.GET_FAIL, "获取失败", null);
    }

    @PostMapping
    public Result addCoa(@RequestBody machine mac, @RequestHeader("token") String token) {
        if (!JwtUtill.VerifyToken(token)) {
            return new Result(Code.ADD_FAIL, "token失效", null);
        }
        if (machine.add(mac)) {
            return new Result(Code.ADD_SUCCESS, "添加成功", null);
        }
        return new Result(Code.ADD_FAIL, "添加失败", null);
    }

    @PutMapping()
    public Result updateCoa(@RequestBody machine mac, @RequestHeader("token") String token) {
        if (!JwtUtill.VerifyToken(token)) {
            return new Result(Code.UPDATE_FAIL, "token失效", null);
        }
        if (machine.update(mac)) {
            return new Result(Code.UPDATE_SUCCESS, "修改成功", null);
        }
        return new Result(Code.UPDATE_FAIL, "修改失败", null);
    }

    @DeleteMapping("/{id}")
    public Result deleteCoa(@PathVariable int id, @RequestHeader("token") String token) {
        if (id < 0) {
            throw new BusinessException(Code.DELETE_FAIL, "无效id: " + id);
        }
        if (!JwtUtill.VerifyToken(token)) {
            return new Result(Code.DELETE_FAIL, "token失效", null);
        }

        if (machine.delete(id)) {
            return new Result(Code.DELETE_SUCCESS, "删除成功", null);
        }
        return new Result(Code.DELETE_FAIL, "删除失败", null);
    }
}
